package com.dengke.springsecurity.impl;

import java.util.List;
import java.util.UUID;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.dengke.springsecurity.dao.ApplicantDAO;
import com.dengke.springsecurity.entity.Applicant;
import com.dengke.springsecurity.model.ApplicantInfo;
@Service
public class ApplicantDAOImpl implements ApplicantDAO {

	@Autowired
	private SessionFactory sessionFactory;

	@Override
	public Applicant findApplicant(String id) {
		Session sesion = sessionFactory.getCurrentSession();
		Criteria criteria = sesion.createCriteria(Applicant.class);
		criteria.add(Restrictions.eq("id", id));
		return (Applicant) criteria.uniqueResult();
	}

	@Override
	public List<ApplicantInfo> listApplicantInfos() {
		String sql = "select new " + ApplicantInfo.class.getName()
				+ " (a.id,a.name,a.email,a.gender,a.position,a.skills)" + " from " + Applicant.class.getName() + " a";

		Session session = sessionFactory.getCurrentSession();
		Query query = session.createQuery(sql);
		return query.list();
	}

	@Override
	public void saveApplicant(ApplicantInfo applicantInfo) {
		String id = applicantInfo.getId();
		Applicant applicant = null;
		if (id != null) {
			applicant = this.findApplicant(id);
		}
		boolean isNew = false;
		if (applicant == null) {
			isNew = true;
			applicant = new Applicant();
			applicant.setId(UUID.randomUUID().toString());
		}
		applicant.setEmail(applicantInfo.getEmail());
		applicant.setGender(applicantInfo.getGender());
		applicant.setName(applicantInfo.getName());
		applicant.setPosition(applicantInfo.getPosition());
		String skillsString = applicantInfo.getSkillsString();
		applicant.setSkills(skillsString);

		if (isNew) {
			Session session = this.sessionFactory.getCurrentSession();
			session.persist(applicant);
		}
	}

	@Override
	public ApplicantInfo findApplicantInfo(String id) {
		Applicant applicant = this.findApplicant(id);
		if (applicant == null) {
			return null;
		}
		return new ApplicantInfo(applicant.getId(), applicant.getName(), applicant.getEmail(), applicant.getPosition(),
				applicant.getGender(), applicant.getSkills());
	}

	@Override
	public void deleteApplicant(String id) {
		Applicant applicant = this.findApplicant(id);
		if (applicant != null) {
			this.sessionFactory.getCurrentSession().delete(applicant);
		}
	}

}
